#include"MyStdio.h"


FILE_*  fopen_(const char* path_name,const char* mod)
{
  int flags = 0 ;
  if(strcmp(mod,"r") == 0)
  {
    flags |= O_RDONLY; 
  }else if(strcmp(mod,"w") == 0) 
  {
    flags |= O_WRONLY | O_CREAT | O_TRUNC;
  }else if(strcmp(mod,"a") == 0)
  {
    flags |= O_WRONLY | O_CREAT | O_APPEND;
  }else 
  {
    //TODO
  }
 
  int fd_ = -1;
  if(flags & O_RDONLY) 
    fd_ = open(path_name,flags);
  else 
    fd_ = open(path_name,flags,0666);
    
  if(fd_ < 0)
  {
    return NULL;
  }
  FILE_* file = (FILE_*)malloc(sizeof(FILE_));
  memset(file->buff,0,sizeof file);
  file->fd = fd_ ; 
  file->flag = SYNC_LINE; 
  file->size = 0 ;
  file->cap = SIZE;
  return file;
}


void fwrite_(FILE_* file,const void* buff,size_t num)
{
  //把要写入的字符串拷贝到缓冲区
  memcpy(file->buff + file->size , buff,num);
  file->size += num; 
  
  if(file->flag == SYNC_NOW)
  {
    fflash_(file);
  }else if(file->flag == SYNC_LINE)
  {
    if(file->buff[file->size - 1] == '\n')
    {
      fflash_(file);
    }

  }else if(file->flag == SYNC_FULL)
  {
    fflash_(file);
  }

}
void fflash_(FILE_* file)
{
  if(file->size > 0 ) write(file->fd,file->buff,file->size);
  fsync(file->fd);
  file->size = 0 ;
}

void fclose_(FILE_* file)
{
  fflash_(file); 
  close(file->fd); 
}
